import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:provider/provider.dart';
import 'package:trade/common/service/router_service/router_table.dart';
import 'package:trade/data/model/user_model.dart';
import 'package:trade/pages/splash_page.dart';
import 'package:flutter_k_chart/generated/l10n.dart' as k_chart;
import 'package:trade/theme/app_theme.dart';
import 'common/config/td_config.dart';

import 'common/service/td_service.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await config.init();
  await service.init();
  runApp(MyApp());
  // 透明状态栏
  if (Platform.isAndroid) {
    final SystemUiOverlayStyle systemUiOverlayStyle = SystemUiOverlayStyle(
      statusBarColor: Colors.transparent,
      systemNavigationBarColor: Colors.transparent,
    );
    SystemChrome.setSystemUIOverlayStyle(systemUiOverlayStyle);
  }
}

class MyApp extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MyAppState();
  }
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    final userModel = UserModel();
    final appProvider = MultiProvider(
      providers: [
        ChangeNotifierProvider<UserModel>.value(
          value: userModel,
        ),
      ],
      child: Builder(
        builder: (ctx) {
          return MaterialApp(
            theme: appTheme.darkThemeData,
            navigatorObservers: [service.router],
            onGenerateRoute: (settings) =>
                service.router.generateRoute(settings),
            builder: EasyLoading.init(builder: _customChild),
            localizationsDelegates: [k_chart.S.delegate],
            locale: Locale.fromSubtags(languageCode: "zh"),
            initialRoute: userModel.info.token.isNotEmpty
                ? RouteName.tradingPage
                : RouteName.loginPage,
          );
        },
      ),
    );
    return appProvider;
  }

  Widget _customChild(BuildContext context, Widget? child) {
    /// 状态栏
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: SystemUiOverlayStyle.light,
      child: GestureDetector(
        child: child,
        onTap: () => _hideKeyboard(context),
      ),
    );
  }

  void _hideKeyboard(BuildContext context) {
    FocusScopeNode currentFocus = FocusScope.of(context);
    if (!currentFocus.hasPrimaryFocus && currentFocus.focusedChild != null) {
      FocusManager.instance.primaryFocus!.unfocus();
    }
  }
}
